<template>
  <!-- 号牌模板 完赛证书模板 -->
  <div class="alertBox">
    <div class="alertCon">
      <div class="alertTit">
        <div class="titCon">编辑模板</div>
        <div class="titFun">
          <el-upload
            class="upLoadBtn"
            :action="actionUrl"
            :on-success="(value)=> picSuccess(value)"
            :before-upload="(file)=> beforeUpload(file)"
            :show-file-list="false"
            name="img"
          >
            <el-button type="text" icon="el-icon-upload">点击上传</el-button>
          </el-upload>
          <span class="line">|</span>
          <el-button type="text" icon="el-icon-circle-plus-outline" @click="addProject">添加项目</el-button>
          <el-button type="text" icon="el-icon-remove-outline" @click="delProject">删除项目</el-button>
          <span class="line">|</span>
          <el-button type="text" icon="el-icon-upload" @click="saveTemp()">保存</el-button>
          <el-button type="text" icon="el-icon-close" class="close" @click="closeTemp()"></el-button>
        </div>
      </div>
      <div class="tempLeft">
        <div class="tempCon" ref="tempBox">
          <img :src="imgUrl" class="upImged" v-if="imgUrl" />
          <span v-else>请上传模板图片;需为jpg格式,大小不得超过500kb</span>
          <VueDragResize
            v-for="(v,i) in itemList"
            :key="i"
            :isActive="v.isActive"
            :w="v.vw"
            :h="v.vh"
            v-on:clicked="dragClick(i)"
            v-on:resizing="resize"
            v-on:dragging="resize"
            :minw="v.minw"
            :minh="v.minh"
            :parentLimitation="true"
            :parentW="v.parentW"
            :parentH="v.parentH"
            :x="v.left"
            :y="v.top"
          >
            <div
              class="itemBox"
              :style="{width: + v.vw+ 'px',height:+v.vh+'px',textAlign:v.align,fontSize:v.size+'px',color:v.color}"
            >
            <!-- lineHeight:+v.vh+'px', -->
              <span v-show="v.name!='erCode'" v-html="v.val"></span>
              <img :src="v.val" alt v-show="v.name=='erCode'" class="tgMa" />
            </div>
          </VueDragResize>
        </div>
      </div>
      <div class="tempRight">
        <el-form label-width="70px" v-if="itemList.length>0">
          <el-form-item label="字段类型">
            <el-select v-model="itemList[actItemI].name" placeholder="请选择" @change="itemChange">
              <el-option
                v-for="(item,i) in projectArr"
                :key="i"
                :label="item.label"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="x：">
            <el-input placeholder="请输入内容" v-model="itemList[actItemI].left" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="y：">
            <el-input placeholder="请输入内容" v-model="itemList[actItemI].top" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="宽度：">
            <el-input placeholder="请输入内容" v-model="itemList[actItemI].vw" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="高度：">
            <el-input placeholder="请输入内容" v-model="itemList[actItemI].vh" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="字体大小">
            <el-input placeholder="请输入内容" v-model="itemList[actItemI].size">
              <template slot="append">
                px
                <el-tooltip class="item" effect="dark" content="最小为12" placement="top">
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="对齐方式">
            <el-select v-model="itemList[actItemI].align" placeholder="请选择">
              <el-option label="left" value="left"></el-option>
              <el-option label="center" value="center"></el-option>
              <el-option label="right" value="right"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="垂直显示" v-if="tempType =='end'">
            <el-select v-model="itemList[actItemI].br" placeholder="请选择" @change="verticalChange">
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="字体颜色">
            <el-color-picker v-model="itemList[actItemI].color"></el-color-picker>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import VueDragResize from "vue-drag-resize";

import sbrImg from "../static/image/sbr.jpg";
// 电子号牌设置项
var numberArr = [
  {
    name: "name",
    label: "姓名",
    val: "张三",
  },
  {
    name: "entryNumber",
    label: "参赛号",
    val: "0001",
  },
  {
    name: "groupName",
    label: "组别",
    val: "100KM",
  },
  {
    name: "sex",
    label: "性别",
    val: "男",
  },
  {
    name: "erCode",
    label: "推广二维码",
    val: sbrImg,
  },
];
// 完赛证书设置项
var endRaceArr = [
  {
    name: "name",
    label: "姓名",
    val: "张三",
  },
  {
    name: "entryNumber",
    label: "参赛号",
    val: "0001",
  },
  {
    name: "groupName",
    label: "组别",
    val: "100KM组",
  },
  {
    name: "sex",
    label: "性别",
    val: "男",
  },
  {
    name: "rank",
    label: "排名",
    val: "1",
  },
  {
    name: "sexRank",
    label: "性别排名",
    val: "2",
  },
  {
    name: "useTime",
    label: "比赛用时",
    val: "00:00:00",
  },
  {
    name: "useHH",
    label: "比赛用时·小时",
    val: "00",
  },
  {
    name: "useMM",
    label: "比赛用时·分钟",
    val: "01",
  },
  {
    name: "useSS",
    label: "比赛用时·秒",
    val: "02",
  },
  {
    name: "distance",
    label: "距离",
    val: "42.195",
  },
  {
    name: "erCode",
    label: "推广二维码",
    val: sbrImg,
  },
];
// 活动证书设置项
var actRaceArr = [
  {
    name: "name",
    label: "姓名",
    val: "张三",
  },
  {
    name: "entryNumber",
    label: "参赛号",
    val: "0001",
  },
  {
    name: "groupName",
    label: "组别",
    val: "100KM组",
  },
  {
    name: "sex",
    label: "性别",
    val: "男",
  },
  {
    name: "erCode",
    label: "推广二维码",
    val: sbrImg,
  },
];
let init = {
  align: "left",
  isActive: false, //是否被选中
  vw: 100, // 选框的宽度
  vh: 100, // 选框的高度
  top: 0, //选框距左上角高度
  left: 0, //选框距左上角宽度
  minw: 30, // 选框最小宽度
  minh: 10, // 选框最小高度
  parentW: 100, //父节点宽度
  parentH: 100, //父节点高度
  color: "#fff", // 颜色
  size: 16, //字体大小
  br:'0', //是否垂直显示
};
numberArr.forEach((v) => {
  v = Object.assign(v, init);
});
export default {
  components: { VueDragResize },
  props: {
    tempType: {
      type: String,
      default: "entry",
    },
    modelId: { type: Number, default: 0 },
  },
  data() {
    return {
      actionUrl: this.$url + "/sbr/match/uploadImg",
      imgUrl: "",
      itemList: [],
      projectArr: [],
      actItemI: 0,
      bigW: 100, // 父节点宽度
      bigH: 100, // 父节点高度
    };
  },
  methods: {
    verticalChange(){
      let txt=this.itemList[this.actItemI].val
      txt=txt.replace(/<br>/g,'')
      if(this.itemList[this.actItemI].br==1){
        this.itemList[this.actItemI].val=txt.split('').join('<br>')
      }else{
        this.itemList[this.actItemI].val=txt
      }
    },
    picSuccess(v) {
      this.getImg(v.data.filePath);
    },
    beforeUpload(file) {
      if (this.imgUrl) {
        let pp = this.imgUrl.split("/");
        pp = this.$Base64.encode(pp[pp.length - 1]);
        this.$axios.get("/sbr/match/delImg?fileName=" + pp);
      }
      const isJPG = file.type === "image/jpeg";
      const isLt5 = file.size / 1024 / 1024 <= 1;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt5) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      return isJPG && isLt5;
    },
    getImg(url, items) {
      var img = new Image();
      img.src = url;
      img.onload = () => {
        var w = img.width;
        var h = img.height;
        var maxWidth = 530;
        var maxHeight = 530;
        var wb = w / maxWidth;
        var hb = h / maxHeight;
        if (wb >= hb) {
          //宽度固定，高度缩放
          img.width = maxWidth;
          img.height = h / wb;
        } else {
          //高度固定，宽度缩放
          img.height = maxHeight;
          img.width = w / hb;
        }
        this.$refs.tempBox.style.width = img.width + "px";
        this.$refs.tempBox.style.height = img.height + "px";
        this.bigW = img.width;
        this.bigH = img.height;
        this.imgUrl = url;
        if (items) {
          items.forEach((v) => {
            v.isActive = false;
            v.minw = 30;
            v.minh = 10;
            v.parentW = img.width;
            v.parentH = img.height;
          });
          items[0].isActive = true;
          this.actItemI = 0;
          this.itemList = items;
        } else {
          if (this.itemList.length == 0) this.addProject();
        }
      };
    },
    resize(newRect) {
      this.itemList[this.actItemI].vw = newRect.width;
      this.itemList[this.actItemI].vh = newRect.height;
      this.itemList[this.actItemI].top = newRect.top;
      this.itemList[this.actItemI].left = newRect.left;
    },
    dragClick(i) {
      this.itemList.forEach((v) => {
        v.isActive = false;
      });
      this.itemList[i].isActive = true;
      this.actItemI = i;
    },
    // 添加项目
    addProject() {
      if (!this.imgUrl) {
        this.$message.error("请先选择模板图片");
        return false;
      }
      numberArr[0].parentW = this.bigW;
      numberArr[0].parentH = this.bigH;
      numberArr[0].isActive = true;
      this.itemList.forEach((v) => {
        v.isActive = false;
      });
      this.itemList.push(JSON.parse(JSON.stringify(numberArr[0])));
      this.actItemI = this.itemList.length - 1;
    },
    // 删除项目
    delProject() {
      if (this.itemList.length == 1) {
        this.$message.error("最少设置一项");
        return false;
      }
      this.itemList.splice(this.actItemI, 1);
      this.actItemI = 0;
    },
    // 切换字段类型
    itemChange() {
      let v = this.projectArr.find((v) => {
        return v.name == this.itemList[this.actItemI].name;
      });
      this.itemList[this.actItemI].val = v.val;
      this.itemList[this.actItemI].label = v.label;
    },
    // 保存模板
    saveTemp() {
      if(!this.imgUrl){
        this.$message.error("请上传模板图片")
        return false
      }
      let oo = {
        imgUrl: this.imgUrl,
        items: "",
        height: this.bigH,
        width: this.bigW,
      };
      if (this.modelId != 0) oo.id = this.modelId;
      let items = this.itemList.map((v) => {
        return {
          name: v.name,
          label: v.label,
          val: v.val,
          align: v.align,
          vw: v.vw, // 选框的宽度
          vh: v.vh, // 选框的高度
          top: v.top, //选框距左上角高度
          left: v.left, //选框距左上角宽度
          color: v.color, // 颜色
          size: v.size, //字体大小
          br:v.br?v.br:''
        };
      });
      oo.items = JSON.stringify(items);
      this.$axios.post("/sbr/match/putCertificate", oo).then((res) => {
        if (this.modelId != 0) this.$emit("update:modelId", this.modelId);
        else this.$emit("update:modelId", res.data.data);
        this.$emit("update:showTemp", false);
      });
    },
    closeTemp() {
      this.$emit("update:showTemp", false);
    },
    // 获取模板
    getTemp() {
      this.$axios
        .get("/sbr/match/getCertificate?id=" + this.modelId)
        .then((res) => {
          let rr = res.data.data;
          let items = JSON.parse(rr.items);
          this.getImg(rr.imgUrl, items);
        });
    },
  },
  mounted() {
    // 号牌则为 numberArr , 完赛证书为 endRaceArr
    if (this.tempType == "entry") {
      this.projectArr = numberArr;
    } else if (this.tempType == "end") {
      this.projectArr = endRaceArr;
    }else if (this.tempType == "act") {
      this.projectArr = actRaceArr;
    }
    if (this.modelId != 0) {
      this.getTemp();
    }
    // this.getImg('http://www.lvtutech.com:9090/1634787900503_sg_nov14.jpg')
  },
};
</script>
<style scoped>
/* @import url(); 引入公共css类 */
.alertBox {
  display: flex;
  align-items: center;
  justify-content: center;
}
.alertCon {
  width: 800px;
  height: 600px;
  background-color: #e0e0e0;
}
.alertTit {
  width: calc(100% - 20px);
  height: 50px;
  line-height: 50px;
  padding: 0 10px;
  font-size: 20px;
}
.titCon {
  float: left;
}
.titFun {
  float: right;
}
.upLoadBtn {
  float: left;
}
.line {
  display: inline-block;
  margin: 0 5px;
  color: #66b1ff;
  font-weight: 500;
}
.close {
  color: #fff;
  font-size: 22px;
}
.tempLeft {
  width: 550px;
  height: 550px;
  background-color: #f2f2f2;
  display: flex;
  align-items: center;
  justify-content: center;
  float: left;
}
.tempRight {
  width: calc(250px - 12px);
  padding: 0 6px;
  height: 550px;
  float: right;
}
.tempCon {
  position: relative;
  overflow: hidden;
}
.upImged {
  width: 100%;
  height: 100%;
}
.itemBox {
  background-color: rgba(255, 255, 0, 0.4);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.itemBox >span{
  width: 100%;
}
.valSpan {
  float: left;
}
.tgMa {
  width: 100%;
  height: 100%;
}
</style>